package org.gwt.project.tools;

import static org.eclipse.core.resources.ResourcesPlugin.getWorkspace;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.wst.common.project.facet.core.IDelegate;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
import org.gwt.project.tools.quickfix.Generator;

public class ToolsInstall implements IDelegate {

	@Override
	public void execute(IProject project, IProjectFacetVersion version,
			Object config, IProgressMonitor monitor) throws CoreException {
		
		// Collect current set of natures
		IProjectDescription description = project.getDescription();
		
		// Only install once
		if (description.hasNature(ToolsNature.ID)) return;
		
		// Add tools nature 
		String[] natures = description.getNatureIds();
		String[] newNatures = new String[natures.length + 1];
		System.arraycopy(natures, 0, newNatures, 0, natures.length);
		newNatures[natures.length] = ToolsNature.ID;
		
		// Validate (fails if one or more required natures is missing) 
		IStatus status = getWorkspace().validateNatureSet(newNatures);
		
		// Check the status
		if (status.getCode() == IStatus.OK) {
			description.setNatureIds(newNatures);
			project.setDescription(description, null);
		} else {
			
			// Add problem marker
			Generator.createProblemMarker(
					project,
					Generator.PROJECT,
					status.getMessage(), 
					IMarker.SEVERITY_ERROR,
					IMarker.PRIORITY_HIGH,
					project.getName());			
			
			// Installation not possible
			throw new CoreException(status);

		}
		
	}

}
